import 'package:flutter/material.dart';
import '../../models/community_post.dart';
import '../../widgets/image_preview.dart';
import '../../widgets/comment_section.dart';
import '../../widgets/floating_action_bar.dart';
import '../../services/community_service.dart';
import '../../utils/date_formatter.dart';

class CommunityDetailPage extends StatefulWidget {
  final CommunityPost post;

  const CommunityDetailPage({
    super.key,
    required this.post,
  });

  @override
  State<CommunityDetailPage> createState() => _CommunityDetailPageState();
}

class _CommunityDetailPageState extends State<CommunityDetailPage> {
  late CommunityPost _post;
  final ScrollController _scrollController = ScrollController();
  final PageController _imagePageController = PageController();
  final CommunityService _communityService = CommunityService();
  bool _isFavorited = false;
  int _currentImageIndex = 0;
  final GlobalKey<CommentSectionState> _commentSectionKey = GlobalKey();
  

  @override
  void initState() {
    super.initState();
    _post = widget.post;
    _isFavorited = _post.isFavorited;
  }

  @override
  void dispose() {
    _scrollController.dispose();
    _imagePageController.dispose();
    super.dispose();
  }



  void _toggleLike() async {
    try {
      final result = await _communityService.toggleLikePost(_post.id);
      
      if (result['success'] == true) {
        setState(() {
          _post = _post.copyWith(
            isLiked: !_post.isLiked,
            likeCount: _post.isLiked ? _post.likeCount - 1 : _post.likeCount + 1,
          );
        });
        
        // ignore: use_build_context_synchronously
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text(_post.isLiked ? '已点赞' : '已取消点赞'),
            duration: const Duration(seconds: 1),
          ),
        );
      } else {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text(result['message'] ?? '操作失败')),
        );
      }
    } catch (e) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('操作失败: ${e.toString()}')),
      );
    }
  }

  void _toggleFavorite() async {
    try {
      final result = await _communityService.toggleFavoritePost(_post.id);
      
      if (result['success'] == true) {
        setState(() {
          _isFavorited = !_isFavorited;
          _post = _post.copyWith(isFavorited: _isFavorited);
        });
        
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text(_isFavorited ? '已收藏' : '已取消收藏'),
            duration: const Duration(seconds: 1),
          ),
        );
      } else {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text(result['message'] ?? '操作失败')),
        );
      }
    } catch (e) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('操作失败: ${e.toString()}')),
      );
    }
  }





  // 构建悬浮底部操作栏
  Widget _buildFloatingBottomBar() {
    return FloatingActionBar(
      isLiked: _post.isLiked,
      likeCount: _post.likeCount,
      isFavorited: _isFavorited,
      commentCount: _post.commentCount,
      onLike: _toggleLike,
      onFavorite: _toggleFavorite,
      onComment: () {
        _commentSectionKey.currentState?.showCommentInputBottomSheet();
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      extendBody: true, // 推荐开启
      backgroundColor: Colors.white,
      resizeToAvoidBottomInset: true, // 键盘弹出时调整布局
      bottomNavigationBar: _buildFloatingBottomBar(),
      appBar: AppBar(
        backgroundColor: Colors.white,
        elevation: 0,
        leading: IconButton(
          icon: const Icon(Icons.arrow_back, color: Colors.black87),
          onPressed: () => Navigator.of(context).pop(),
        ),
        title: const Text(
          '动态详情',
          style: TextStyle(
            color: Colors.black87,
            fontWeight: FontWeight.w600,
          ),
        ),
        actions: [
          IconButton(
            icon: Icon(
              _isFavorited ? Icons.bookmark : Icons.bookmark_border,
              color: _isFavorited ? Colors.blue[600] : Colors.black54,
            ),
            onPressed: _toggleFavorite,
          ),
          IconButton(
            icon: const Icon(Icons.share, color: Colors.black54),
            onPressed: () {
              ScaffoldMessenger.of(context).showSnackBar(
                const SnackBar(
                  content: Text('分享功能开发中'),
                  duration: Duration(seconds: 1),
                ),
              );
            },
          ),
        ],
      ),
      body: Column(
        children: [
          Expanded(
            child: SingleChildScrollView(
              controller: _scrollController,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // 作者信息
                  _buildAuthorInfo(),
                  
                  // 内容
                  _buildContent(),
                  
                  // 图片
                  if (_post.images.isNotEmpty) _buildImages(),
                  
                  // 标签和位置
                  _buildTagsAndLocation(),
                  
                  const Divider(height: 1),
                  
                  // 评论列表
                  _buildCommentsList(),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildAuthorInfo() {
    return Container(
      padding: const EdgeInsets.all(16),
      child: Row(
        children: [
          CircleAvatar(
            radius: 24,
            backgroundImage: NetworkImage(_post.authorAvatar),
            onBackgroundImageError: (exception, stackTrace) {},
            child: _post.authorAvatar.isEmpty
                ? Icon(Icons.person, size: 24, color: Colors.grey[600])
                : null,
          ),
          const SizedBox(width: 12),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  _post.authorName,
                  style: const TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.w600,
                    color: Colors.black87,
                  ),
                ),
                const SizedBox(height: 4),
                Text(
                  DateFormatter.formatPublishTime(_post.publishTime),
                  style: TextStyle(
                    fontSize: 12,
                    color: Colors.grey[600],
                  ),
                ),
              ],
            ),
          ),
          TextButton(
            onPressed: () {
              ScaffoldMessenger.of(context).showSnackBar(
                const SnackBar(
                  content: Text('关注功能开发中'),
                  duration: Duration(seconds: 1),
                ),
              );
            },
            child: Text(
              '关注',
              style: TextStyle(
                color: Colors.blue[600],
                fontWeight: FontWeight.w500,
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildContent() {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 16),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            _post.title,
            style: const TextStyle(
              fontSize: 18,
              fontWeight: FontWeight.bold,
              color: Colors.black87,
              height: 1.4,
            ),
          ),
          const SizedBox(height: 12),
          Text(
            _post.content,
            style: TextStyle(
              fontSize: 15,
              color: Colors.grey[800],
              height: 1.5,
            ),
          ),
          const SizedBox(height: 16),
        ],
      ),
    );
  }

  Widget _buildImages() {
    return Container(
      height: 300,
      margin: const EdgeInsets.symmetric(horizontal: 16),
      child: Stack(
        children: [
          PageView.builder(
            controller: _imagePageController,
            itemCount: _post.images.length,
            onPageChanged: (index) {
              setState(() {
                _currentImageIndex = index;
              });
            },
            itemBuilder: (context, index) {
              return GestureDetector(
                onTap: () {
                  // 点击图片进行全屏预览
                  Navigator.of(context).push(
                    MaterialPageRoute(
                      fullscreenDialog: true,
                      builder: (context) => ImagePreview(
                        imagePaths: _post.images,
                        initialIndex: index,
                        isNetworkImage: true,
                      ),
                    ),
                  );
                },
                child: ClipRRect(
                  borderRadius: BorderRadius.circular(12),
                  child: Image.network(
                    _post.images[index],
                    fit: BoxFit.cover,
                    errorBuilder: (context, error, stackTrace) {
                      return Container(
                        decoration: BoxDecoration(
                          color: Colors.grey[200],
                          borderRadius: BorderRadius.circular(12),
                        ),
                        child: Icon(
                          Icons.image_not_supported,
                          size: 60,
                          color: Colors.grey[400],
                        ),
                      );
                    },
                  ),
                ),
              );
            },
          ),
          if (_post.images.length > 1)
            Positioned(
              bottom: 12,
              right: 12,
              child: Container(
                padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                decoration: BoxDecoration(
                  color: Colors.black.withOpacity(0.6),
                  borderRadius: BorderRadius.circular(12),
                ),
                child: Text(
                  '${_currentImageIndex + 1}/${_post.images.length}',
                  style: const TextStyle(
                    color: Colors.white,
                    fontSize: 12,
                  ),
                ),
              ),
            ),
        ],
      ),
    );
  }

  Widget _buildTagsAndLocation() {
    return Padding(
      padding: const EdgeInsets.all(16),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          if (_post.tags.isNotEmpty) ...[
            Wrap(
              spacing: 8,
              runSpacing: 8,
              children: _post.tags.map((tag) {
                return Container(
                  padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
                  decoration: BoxDecoration(
                    color: Colors.blue[50],
                    borderRadius: BorderRadius.circular(16),
                  ),
                  child: Text(
                    '#$tag',
                    style: TextStyle(
                      fontSize: 13,
                      color: Colors.blue[600],
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                );
              }).toList(),
            ),
            const SizedBox(height: 12),
          ],
          Row(
            children: [
              if (_post.location.isNotEmpty) ...[
                Icon(Icons.location_on, size: 16, color: Colors.grey[600]),
                const SizedBox(width: 4),
                Text(
                  _post.location,
                  style: TextStyle(
                    fontSize: 13,
                    color: Colors.grey[600],
                  ),
                ),
              ],
              const Spacer(),
            ],
          ),
        ],
      ),
    );
  }

  
  Widget _buildCommentsList() {
    return Container(
      padding: const EdgeInsets.all(16),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          
          // 评论组件
          CommentSection(
            key: _commentSectionKey,
            postId: _post.id,
            postType: 'community',
            onCommentCountChanged: (count) {
              setState(() {
                _post = _post.copyWith(commentCount: count);
              });
            },
          ),
        ],
      ),
    );
  }


}